package app.controllers.product;

import app.Const;
import app.models.basic.Dict;
import app.models.product.ProductAttr;
import app.models.sys.User;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;
import goja.security.shiro.AppUser;
import goja.security.shiro.Securitys;

import java.util.List;

/**
 * 产品属性管理
 * iuhui on 15/2/12.
 */
public class AttrController extends Controller{

    @Before(GET.class)
    public void index(){

        List<Dict> datatypes = Dict.dao.dataTypes();
        setAttr("datatype_json", JsonKit.toJson(datatypes));
    }

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist(){
        final DTCriterias criterias = getCriterias();
        renderDataTables(criterias,ProductAttr.class);
    }

    @Before(GET.class)
    public void create() {
        ProductAttr attr = new ProductAttr();
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        List<Dict> datatypes = Dict.dao.dataTypes();
        setAttr("datatypes", datatypes);
        setAttr("attr",attr);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        ProductAttr attr = ProductAttr.dao.findById(id);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        List<Dict> datatypes = Dict.dao.dataTypes();
        setAttr("datatypes", datatypes);
        setAttr("attr",attr);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        AppUser<User> loginUser = Securitys.getLogin();
        ProductAttr attr = getModel(ProductAttr.class,"attr");
        if (DaoKit.isNew(attr)) {
            attr.set(Const.FIELD_STATUS, 1);
            attr.save();
        } else {
            attr.update();
        }
        redirect("/product/attr");
    }


    public void delete(){
        int id = getParaToInt(0, 0);
        boolean status = ProductAttr.dao.deleteById(id);
        if(status){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }

    /**
     * 设置启用禁用状态
     */
    @Before(GET.class)
    public void setStatus(){
        String id = getPara("id","0");
        String set_val = getPara("set_val");
        boolean updateStatus = ProductAttr.dao.updateStatus(set_val, id);
        if(updateStatus){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }


}
